/**
 * @author rxliuli
 */
const app = (() => {
    const {
        DateFormatter: {
            dateFormatter,
        },
        AsyncArray,
        arrayToMap,
        groupBy,
        sortBy,
        compare,
    } = rx
    return new BaseValidateVue({
        el: '#app',
        data() {
            return {
                baseCustomer: new BaseCustomer({
                    officer: '',
                    userType: 1,
                    unitNature: 1,
                    idType: 1,
                }),
                baseHousesHoldInfo: new BaseHousesHoldInfo({
                    frameInfoId: '',
                    userType: 1,
                    setMode: 1,
                    businessType: 1,
                    virtualHostName: '',
                    virtualHostState: '',
                    virtualHostType: '',
                    virtualHostAddress: '',
                    virtualHostManagement: '',
                }),
                baseServiceInfo: new BaseServiceInfo({
                    serviceContentSet: new Set(),
                    serviceContent: null,
                    businessType: 1,
                    regType: '',
                }),
                baseServiceDomainSet: new Set(),
                domain: null,
                currentSelectDomainList: [],
                baseIpTransInfoSet: new Set([new BaseIpTransInfo()]),
                baseFrameInfoList: [],
                baseHouseOfficerList: [],
                provinceCityArea: {
                    provinceMap: new Map(),
                    cityMap: new Map(),
                    areaMap: new Map(),
                },
                serviceContentShow: false,
                domainListShow: false,
                resOtherValidator: false,
                ruleList: [
                    new ValidateObject({
                        ruleName: 'checkIpArr',
                        validate: this.checkIpArrValidate,
                    }),
                    new ValidateObject({
                        ruleName: 'checkPrivateIpArr',
                        validate: this.checkPrivateIpArrValidate,
                    }),
                ],
                baseFrameInfoMap: new Map(),
                vhNameShow: false,
                vhTypeShow: false,
                vhAddressShow: false,
                vhManagementShow: false,
                virtualHostValidator: false,
            }
        },
        methods: {
            /**
             * 添加 ip 地址转换信息
             */
            addBaseIpAddressInfo() {
                this.baseIpTransInfoSet = new Set(this.baseIpTransInfoSet).add(new BaseIpTransInfo())
            },
            deleteBaseIpTransInfo(index) {
                this.baseIpTransInfoSet = new Set(Array.from(this.baseIpTransInfoSet.values())
                    .filter((_, i) => i !== index))
            },
            /**
             * 添加域名信息
             */
            addDomain() {
                if (!rx.stringValidator.isDomain(this.domain)) {
                    return
                }
                const set = new Set(this.baseServiceDomainSet)
                if (([...set]).some(baserServiceDomain => baserServiceDomain.domain === this.domain)) {
                    return
                }
                set.add({
                    domain: this.domain,
                })
                this.baseServiceDomainSet = set
                this.domain = null
            },
            /**
             * 删除域名
             */
            deleteDomain() {
                this.baseServiceDomainSet = new Set(
                    ([...this.baseServiceDomainSet])
                        .filter(baseServiceDomain => !this.currentSelectDomainList.includes(baseServiceDomain.domain)),
                )
            },
            /**
             * 点击服务内容复选框
             */
            checkedServiceContent($event) {
                const value = $event.target.value
                const serviceContentSet = new Set(this.baseServiceInfo.serviceContentSet)
                if ($event.target.checked) {
                    serviceContentSet.add(value)
                    this.baseServiceInfo.serviceContentSet = serviceContentSet
                } else {
                    serviceContentSet.delete(value)
                    this.baseServiceInfo.serviceContentSet = serviceContentSet
                }
            },
            /**
             * 更新客户信息
             */
            async addBaseHousesHoldInfoByCustomerId() {
                if (this.baseCustomer.userType === 1) {
                    if (this.baseServiceInfo.serviceContentSet.size === 0) {
                        this.serviceContentShow = true;
                        this.resOtherValidator = true
                    }
                    if (this.baseServiceDomainSet.size === 0) {
                        this.domainListShow = true;
                        this.resOtherValidator = true
                    }
                    if (this.baseHousesHoldInfo.virtualHostName !== '' || this.baseHousesHoldInfo.virtualHostType !== '' || this.baseHousesHoldInfo.virtualHostAddress !== '' || this.baseHousesHoldInfo.virtualHostManagement !== '') {
                        if (this.baseHousesHoldInfo.virtualHostName === '') {
                            this.vhNameShow = true
                            this.virtualHostValidator = true
                        }
                        if (this.baseHousesHoldInfo.virtualHostType === '') {
                            this.vhTypeShow = true
                            this.virtualHostValidator = true
                        }
                        if (this.baseHousesHoldInfo.virtualHostAddress === '') {
                            this.vhAddressShow = true
                            this.virtualHostValidator = true
                        }
                        if (this.baseHousesHoldInfo.virtualHostManagement === '') {
                            this.vhManagementShow = true
                            this.virtualHostValidator = true
                        }
                    }
                }
                if (!await this.$validator.validateAll() || this.resOtherValidator || this.virtualHostValidator) {
                    this.resOtherValidator = false
                    this.virtualHostValidator = false
                    rxPrompt.dangerMsg("输入存在错误！");
                    return
                }
                if (await ajaxOption({
                        res: baseCustomerApi.addBaseHousesHoldInfoByCustomerId({
                            id: this.baseCustomer.id,
                            userType: this.baseCustomer.userType,
                            baseHousesHoldInfo: {
                                ...this.baseHousesHoldInfo,
                                distributeTime: dateFormatter.format(this.baseHousesHoldInfo.distributeTime),
                            },
                            baseServiceInfo: {
                                ...this.baseServiceInfo,
                                registerDate: dateFormatter.format(this.baseServiceInfo.registerDate),
                                expireDate: dateFormatter.format(this.baseServiceInfo.expireDate),
                            },
                            baseServiceDomainList: [...this.baseServiceDomainSet],
                            baseIpTransInfoList: [...this.baseIpTransInfoSet],
                        }),
                        danger: '新增服务信息失败',
                        success: '新增服务信息成功，即将返回列表页面',
                    })) {
                    forward('/basic-data/admin_user_info')
                }
            },
            /**
             * 初始化数据
             */
            async initialData() {
                this.baseHouseOfficerList = await baseHouseOfficerApi.selectList()
                this.baseCustomer = forward.getData()
                let bfi = await baseFrameInfoApi.selectListAppendHouseName(this.baseCustomer.idcId)
                this.baseCustomer.houseId = bfi[0].houseId
                this.baseFrameInfoMap = arrayToMap(bfi, 'id', 'frameName')
                this.provinceCityArea = {
                    provinceMap: arrayToMap(await sysConfProvinceApi.selectList(), ({id}) => id, ({name}) => name),
                    cityMap: groupBy(await sysConfCityApi.selectList(), ({provinceId}) => provinceId, (res, {id, name}) => res.set(id, name), () => new Map()),
                    areaMap: groupBy(await sysConfAreaApi.selectList(), ({cityId}) => cityId, (res, {id, name}) => res.set(id, name), () => new Map()),
                }
            },
            createValidateList() {
                return this.ruleList;
            },
            async checkIpArrValidate(internetEndIp, args) {
                const baseIpTransInfo = ([...this.baseIpTransInfoSet]).filter(BaseIpTransInfo => BaseIpTransInfo.internetEndIp === internetEndIp)
                const {internetStartIp = ''} = baseIpTransInfo[0];
                const fn = val => val.split('.').slice(0, 3)
                return compare(fn(internetStartIp), fn(internetEndIp))
            },
            async checkPrivateIpArrValidate(privateEndIp, args) {
                const baseIpTransInfo = ([...this.baseIpTransInfoSet]).filter(BaseIpTransInfo => BaseIpTransInfo.privateEndIp === privateEndIp)
                const {privateStartIp = ''} = baseIpTransInfo[0];
                const fn = val => val.split('.').slice(0, 3)
                return compare(fn(privateStartIp), fn(privateEndIp))
            },
            updateServiceContent() {
                const val = this.baseServiceInfo.serviceContentSet
                this.baseServiceInfo.serviceContent = val && sortBy([...val], i => parseInt(i)).join(',')
            },
        },
        computed: {
            fieldFormatter() {
                return fieldFormatter
            },
            provinceMap() {
                return this.provinceCityArea.provinceMap
            },
            cityMap() {
                return this.provinceCityArea.cityMap.get(this.baseServiceInfo.houseProvince) || new Map()
            },
            areaMap() {
                return this.provinceCityArea.areaMap.get(this.baseServiceInfo.houseCity) || new Map()
            },
        },
        watch: {
            'baseServiceInfo.serviceContentSet': function (val) {
                this.serviceContentShow = false
                this.updateServiceContent()
            },
            'baseServiceDomainSet': function (val) {
                this.domainListShow = false
            },
            'baseHousesHoldInfo.virtualHostName': function (val) {
                this.vhNameShow = false
            },
            'baseHousesHoldInfo.virtualHostType': function (val) {
                this.vhTypeShow = false
            },
            'baseHousesHoldInfo.virtualHostAddress': function (val) {
                this.vhAddressShow = false
            },
            'baseHousesHoldInfo.virtualHostManagement': function (val) {
                this.vhManagementShow = false
            },
        },
        async mounted() {
            await this.initialData()
        },
    })
})()